using System;
using System.Collections.Generic;
using Blog.Core.Entities;
using Blog.Infrastructure.DataAcces.MetaBlog;
using Blog.Infrastructure.DataAcces.Repositories.Abstractisations;
using NHibernate;
using NHibernate.Criterion;
using Category = Blog.Core.Entities.Category;

namespace Blog.Infrastructure.DataAcces.Repositories.Implementaions
{
    public class ArticleRepository:Repository<Article>,IArticleRepository
    {
        public ArticleRepository(ISessionFactory sessionFactory) : base(sessionFactory)
        {
        }


        public IList<Article> Latest(long itemsNumber)
        {
            return _session
                .CreateCriteria(typeof(Article))
                .Add(Expression.Le("Date", DateTime.Now))
                .AddOrder(Order.Desc("Date"))
                .SetMaxResults((int)itemsNumber)
                .List<Article>();
        }

        public IList<Article> MostPopular(long itemsNumber)
        {
            return _session
                .CreateCriteria(typeof(Article))
                .AddOrder(Order.Desc("Views"))
                .SetMaxResults((int)itemsNumber)
                .List<Article>();
        }

        public IList<Article> Archive(int page, int range)
        {
            return _session
                .CreateCriteria(typeof(Article))
                .SetFirstResult((page - 1) * range)
                .SetMaxResults(range).List<Article>();

        }

        public IList<Article> ByCategory(string cat)
        {
            return _session
                .CreateCriteria(typeof (Article))
                .Add(Restrictions.InsensitiveLike("Categories","%" +cat+ "%"))
                .AddOrder(Order.Desc("Date"))
                .List<Article>();
        }

        public IList<Category> Categories()
        {
            return _session
                .CreateCriteria(typeof (Category))
                .List<Category>();
        }

        public int NewCategory(WordpressCategory category)
        {
            var cat = new Category { Name = category.name };

            _session.SaveOrUpdate(cat);

            return cat.Id;

        }
    }
}